<template>
  <drag-modal
    title="查看截屏"
    :width="1024"
    :visible="visible"
    :destroyOnClose="true"
    :maskClosable="false"
    :centered="true"
    @cancel="cancel"
  >
    <a-row>
      <a-col :span="24" v-if="!canRefresh" style="text-align: center;background-color: #0086e5;">
        <img :src="loadingImgUrl" style="width: 440px; height: 330px;"/>
      </a-col>
      <a-col :span="24" v-else>
        <img :src="form.url" style="width: 100%;"/>
      </a-col>
    </a-row>
    <template slot="footer">
      <a-button v-if="form.id" :loading="!canRefresh" icon="sync" @click="refresh"></a-button>
      <a-button @click="cancel">关闭</a-button>
    </template>
  </drag-modal>
</template>

<script>
import {terminalService, commandService} from '@/services'
import CommandConstant from '@/constant/terminal-command'
export default {
  name: 'ScreenshotModal',
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      url: undefined,
      canRefresh: false,
      timer: undefined,
      loadingImgUrl: require('../../../../assets/img/loading.gif'),
      form: {
        id: undefined,
        url: undefined
      }
    }
  },
  methods: {
    cancel() {
      this.$emit('cancel', CommandConstant.TERMINAL_COMMAND_QUERY_SCREENSHOT)
      this.form.id = undefined
      this.form.url = undefined
      if (this.timer) {
        clearInterval(this.timer)
      }
    },
    pullScreenshot() {
      this.loading = true
      this.form.url = undefined
      const params = {
        ids: [this.form.id]
      }
      commandService.pullScreenshot(JSON.stringify(params)).then(res => {
        const result = res.data
        if (result.code === 200) {
          this.$message.success('拉取指令已发送')
          this.startQueryAction()
          this.canRefresh = false
        }
      }).finally(this.loading = false)
    },
    queryScreenshot() {
      this.loading = true
      const params = {
        id: this.form.id
      }
      terminalService.queryScreenshot(JSON.stringify(params)).then(res => {
        const result = res.data
        if (result.code === 200 && result.data && result.data.url) {
          this.$message.success('拉取截屏成功')
          this.form.url = result.data.url
          this.canRefresh = true
          if (this.timer) {
            clearInterval(this.timer)
          }
          this.timer = null
        }
      }).finally(this.loading = false)
    },
    startQueryAction() {
      this.queryScreenshot()
      this.timer = setInterval(() => {
        this.queryScreenshot()
      }, 5000)
    },
    refresh() {
      this.pullScreenshot()
    }
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
    this.timer = null
  },
  mounted() {

  }
}
</script>
<style scoped lang="less">
  /deep/.ant-modal-body {
    padding: 0;
  }
</style>